using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;

namespace Macaw.Spf2010.ResourceListSolution.Features.Feature1
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("bc5c8f29-b144-414c-85aa-b8707880eea5")]
    public class Feature1EventReceiver : SPFeatureReceiver
    {
        private const string OWNER = "Macaw.Spf2010.ResourceListSolution.FeatureExpressionBuilder";

        private const string EXPRESSIONBUILDERPREFIX = "ResourceList";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            SPWebConfigModification configmod_Expressionbuilder = new SPWebConfigModification();
            configmod_Expressionbuilder.Path = "configuration/system.web/compilation/expressionBuilders";
            configmod_Expressionbuilder.Name = string.Format("add[@expressionPrefix='{0}']", EXPRESSIONBUILDERPREFIX);
            configmod_Expressionbuilder.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            configmod_Expressionbuilder.Value = string.Format("<add expressionPrefix=\"{0}\" type=\"{1}\"/>", EXPRESSIONBUILDERPREFIX, typeof(ResourceListExpressionBuilder).AssemblyQualifiedName );
            configmod_Expressionbuilder.Owner = OWNER;

            webapp.WebConfigModifications.Add(configmod_Expressionbuilder);

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            webapp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
        }


        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webapp = properties.Feature.Parent as SPWebApplication;
            if (webapp == null) return;

            for (int idx = webapp.WebConfigModifications.Count - 1; idx >= 0; idx--)
            {
                SPWebConfigModification conmod = webapp.WebConfigModifications[idx];
                if (string.Equals(conmod.Owner, OWNER, StringComparison.InvariantCultureIgnoreCase) )
                {
                    webapp.WebConfigModifications.RemoveAt(idx);
                }
            }

            webapp.Update(); // Important. Otherwise webconfigmods can be removed upon activating other features
            webapp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications(); 
        }

    }
}
